#!/usr/bin/env python
# coding: utf-8

# # 导入数据

# In[60]:


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import Normalizer


# In[19]:


data = pd.read_csv('./Wholesale customers data.csv')
data.head()


# In[20]:


data.info()


# In[21]:


data.describe()


# In[71]:


data_ = Normalizer().fit_transform(data.iloc[:,2:])
data_


# # 适用轮廓系数找到最优K

# In[72]:


from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score


# In[73]:


score = []
for i in range(2,7):
    cluster = KMeans(n_clusters=i,random_state=0).fit(data_)
    score.append(silhouette_score(data_,cluster.labels_))
plt.plot(range(2,7),score)
plt.xlabel(xlabel='k')
plt.ylabel(ylabel='score')


# # 建模及可视化分析

# In[89]:


cluster = KMeans(n_clusters=3,random_state=0).fit(data_)
cluster_center = pd.DataFrame(cluster.cluster_centers_,columns=['Fresh','Milk','Grocery','Frozen','Detergents_Paper','Delicassen'])
cluster_center


# In[86]:


labels_counts = pd.Series(cluster.labels_).value_counts()
plt.pie(labels_counts.values,autopct='%.f%%')
plt.legend(labels_counts.index)


# In[95]:


cluster_center.plot.bar()


# In[ ]:




